#!/bin/bash
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/alias.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_and_pip_settings.sh"

export CURRENT_APP_PATH="${LMD_APPS_DIR}/f5-tts"
echo 'App Dir: '${CURRENT_APP_PATH}

cd "$CURRENT_APP_PATH"

if [ -z "$HF_ENDPOINT" ] && [ -n "$HF_MIRROR" ]; then
    export HF_ENDPOINT="$HF_MIRROR"
fi

if [ -f /etc/os-release ]; then
    echo "Linux"
elif [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
    echo "macOS"
    # add minconda to PATH
    export PATH=$PATH:${MINICONDA_DIR}/bin/
elif current_os_is_windows; then
    echo "Windows"
    export PATH=$PATH:${MINICONDA_DIR}/Scripts/
else
    echo "Unknown OS"
    exit 1
fi

CONDA_PREFIX="./venv"
echo "global var HF_HOME: "$HF_HOME
DEFAULT_MODEL_DIR="$HOME/.cache/huggingface/hub/models--SWivid--F5-TTS"

if [ -d "$DEFAULT_MODEL_DIR" ]; then
    echo "$DEFAULT_MODEL_DIR found. Use default Dir"
else
    echo "$DEFAULT_MODEL_DIR dose not found."
    export HF_HOME="$CURRENT_APP_PATH/ckpts"
    echo "change HF_HOME:"$HF_HOME
fi

export GRADIO_TEMP_DIR="$CURRENT_APP_PATH/temp"


function install_ffmpeg {
  source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_ffmpeg.sh"
}

function check_ffmpeg_and_install_win {
  PROGRAMS=("ffmpeg" "ffprobe")
  missing_programs=0

  for PROGRAM in "${PROGRAMS[@]}"; do
    if ! command -v ${PROGRAM} >/dev/null 2>&1; then
      $PROGRAM -v
      echo "$PROGRAM not found"
      missing_programs=1
    fi
  done

  if [ $missing_programs -eq 1 ]; then
    echo "need install ffmpeg and ffprobe。"
    install_ffmpeg
  else
    echo "ffmpeg and ffprobe exist"
  fi
}

function check_ffmpeg_and_install {
    if [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
        if conda run -p $CONDA_PREFIX --no-capture-output conda list ffmpeg | grep -q "ffmpeg"; then
            echo "found ffmpeg"
        else
            echo "not found ffmpeg. install it."
            conda run -p $CONDA_PREFIX --no-capture-output conda install -c conda-forge ffmpeg -y
        fi
    elif current_os_is_windows; then
        check_ffmpeg_and_install_win
    fi
}

check_ffmpeg_and_install

conda run -p $CONDA_PREFIX --no-capture-output f5-tts_infer-gradio


